package cn.careerx.app.common.models;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.SqlQuery;
import com.avaje.ebean.SqlRow;
import com.avaje.ebean.SqlUpdate;

import com.baidu.bjf.remoting.protobuf.Codec;
import com.baidu.bjf.remoting.protobuf.FieldType;
import com.baidu.bjf.remoting.protobuf.ProtobufProxy;
import com.baidu.bjf.remoting.protobuf.annotation.Protobuf;

import redis.clients.jedis.Jedis;
import redis.clients.util.SafeEncoder;

public class Org implements Serializable{

	private static final long serialVersionUID = -6077528693693359043L;
	
	private static final Logger logger = LoggerFactory.getLogger(Org.class);
	
	@Protobuf(fieldType=FieldType.STRING, order=1, required=false)
	private String id;
	
	@Protobuf(fieldType=FieldType.STRING, order=2, required=false)
	private String name;
	
	@Protobuf(fieldType=FieldType.STRING, order=3, required=false)
	private String abbr;
	
	@Protobuf(fieldType=FieldType.INT32, order=4, required=false)
	private Integer locationId;
	
	@Protobuf(fieldType=FieldType.STRING, order=5, required=false)
	private String address;
	
	@Protobuf(fieldType=FieldType.INT32, order=6, required=false)
	private Integer size;
	
	@Protobuf(fieldType=FieldType.INT32, order=7, required=false)
	private Integer industry;
	
	@Protobuf(fieldType=FieldType.INT32, order=8, required=false)
	private Integer type;
	
	@Protobuf(fieldType=FieldType.STRING, order=9, required=false)
	private String logoKey;
	
	@Protobuf(fieldType=FieldType.STRING, order=10, required=false)
	private String zipCode;
	
	@Protobuf(fieldType=FieldType.STRING, order=11, required=false)
	private String tel;
	
	@Protobuf(fieldType=FieldType.STRING, order=12, required=false)
	private String fax;
	
	@Protobuf(fieldType=FieldType.STRING, order=13, required=false)
	private String email;
	
	@Protobuf(fieldType=FieldType.STRING, order=14, required=false)
	private String contact;
	
	@Protobuf(fieldType=FieldType.INT32, order=15, required=false)
	private Integer postCount;
	
	@Protobuf(fieldType=FieldType.STRING, order=16, required=false)
	private String payRange;
	
	@Protobuf(fieldType=FieldType.STRING, order=17, required=false)
	private String wxUrl;
	
	@Protobuf(fieldType=FieldType.INT64, order=18, required=false)
	private Long sortValue;
	
	@Protobuf(fieldType=FieldType.STRING, order=19, required=false)
	private String descr;
	
	@Protobuf(fieldType=FieldType.INT64, order=20, required=false)
	private Long createAt;
	
	@Protobuf(fieldType=FieldType.INT64, order=21, required=false)
	private Long updateAt;
	
	@Protobuf(fieldType=FieldType.INT32, order=22, required=false)
	private Integer isValid;
	
	public static Org create(){
		return new Org();
	}
	
	public String getId() {
		return id;
	}

	public Org setId(String id) {
		this.id = id;
		return this;
	}

	public String getName() {
		return name;
	}

	public Org setName(String name) {
		this.name = name;
		return this;
	}

	public String getAbbr() {
		return abbr;
	}

	public Org setAbbr(String abbr) {
		this.abbr = abbr;
		return this;
	}

	public Integer getLocationId() {
		return locationId;
	}

	public Org setLocationId(Integer locationId) {
		this.locationId = locationId;
		return this;
	}

	public String getAddress() {
		return address;
	}

	public Org setAddress(String address) {
		this.address = address;
		return this;
	}

	public Integer getSize() {
		return size;
	}

	public Org setSize(Integer size) {
		this.size = size;
		return this;
	}

	public Integer getIndustry() {
		return industry;
	}

	public Org setIndustry(Integer industry) {
		this.industry = industry;
		return this;
	}

	public Integer getType() {
		return type;
	}

	public Org setType(Integer type) {
		this.type = type;
		return this;
	}

	public String getLogoKey() {
		return logoKey;
	}

	public Org setLogoKey(String logoKey) {
		this.logoKey = logoKey;
		return this;
	}

	public String getZipCode() {
		return zipCode;
	}

	public Org setZipCode(String zipCode) {
		this.zipCode = zipCode;
		return this;
	}

	public String getTel() {
		return tel;
	}

	public Org setTel(String tel) {
		this.tel = tel;
		return this;
	}

	public String getFax() {
		return fax;
	}

	public Org setFax(String fax) {
		this.fax = fax;
		return this;
	}

	public String getEmail() {
		return email;
	}

	public Org setEmail(String email) {
		this.email = email;
		return this;
	}

	public String getContact() {
		return contact;
	}

	public Org setContact(String contact) {
		this.contact = contact;
		return this;
	}

	public Integer getPostCount() {
		return postCount;
	}

	public Org setPostCount(Integer postCount) {
		this.postCount = postCount;
		return this;
	}

	public String getPayRange() {
		return payRange;
	}

	public Org setPayRange(String payRange) {
		this.payRange = payRange;
		return this;
	}

	public String getWxUrl() {
		return wxUrl;
	}

	public Org setWxUrl(String wxUrl) {
		this.wxUrl = wxUrl;
		return this;
	}

	public Long getSortValue() {
		return sortValue;
	}

	public Org setSortValue(Long sortValue) {
		this.sortValue = sortValue;
		return this;
	}

	public String getDescr() {
		return descr;
	}

	public Org setDescr(String descr) {
		this.descr = descr;
		return this;
	}

	public Long getCreateAt() {
		return createAt;
	}

	public Org setCreateAt(Long createAt) {
		this.createAt = createAt;
		return this;
	}

	public Long getUpdateAt() {
		return updateAt;
	}

	public Org setUpdateAt(Long updateAt) {
		this.updateAt = updateAt;
		return this;
	}

	public Integer getIsValid() {
		return isValid;
	}

	public Org setIsValid(Integer isValid) {
		this.isValid = isValid;
		return this;
	}
	
	// 添加Redis
	public boolean toRedis(Jedis jedis) {
		if (id == null) {
			return false;
		}
		try {
			String key = "org:" + id;
			byte[] bKey = SafeEncoder.encode(key);
			Codec<Org> codec = ProtobufProxy.create(Org.class);
			jedis.set(bKey, codec.encode(this));
			return true;
		} catch (Exception e) {
			logger.error("Error persist Org to toRedis : ", e);
		}
		return false;
	}
	
	// 添加索引
	public boolean toEs(Client client){
		try {
			IndexRequestBuilder rb = client.prepareIndex().setIndex("cxorg").setType("org").setId(id);
			JSONObject source = new JSONObject();
			source.put("name", this.getName());
			source.put("abbr", this.getAbbr());
			source.put("status", this.getIsValid());
			source.put("type", 0);
			source.put("updateAt", this.getUpdateAt());
			
			rb.setSource(source.toJSONString());
			IndexResponse resp = rb.execute().actionGet();
			return resp.isCreated();
		} catch (Exception e) {
			logger.error("Error index Org to es, id = "+id, e);
			return false;
		}
	}

	// 从Redis删除
	public static boolean deleteRedis(Jedis jedis, Org org) {
		if (org.getId() == null) {
			return false;
		}
		try {
			String key = "org:" + org.getId();
			byte[] bKey = SafeEncoder.encode(key);
			if (jedis.exists(bKey)) {
				jedis.del(bKey);
			}
			return true;
		} catch (Exception e) {
			logger.error("Error persist Org to deleteRedis : ", e);
		}
		return false;
	}

	// Redis:根据ID获取Org
	public static Org findFromRedisById(Jedis jedis, String id) {
		Org org = null;
		String key = "org:" + id;
		byte[] bKey = SafeEncoder.encode(key);
		Codec<Org> codec = ProtobufProxy.create(Org.class);
		byte[] data = jedis.get(bKey);
		if (data != null) {
			try {
				org = codec.decode(data);
			} catch (Exception ignore) {
				jedis.del(bKey);
			}
		}
		return org;
	}
	
	//把SqlRow类型转化成Org
	public static Org fromDbRow(SqlRow sqlRow) {
		Org result = Org.create().setId(sqlRow.getString("ID"))
				.setName(sqlRow.getString("NAME"))
				.setAbbr(sqlRow.getString("ABBR"))
				.setLocationId(sqlRow.getInteger("LOCATION_ID"))
				.setAddress(sqlRow.getString("ADDRESS"))
				.setSize(sqlRow.getInteger("SIZE"))
				.setIndustry(sqlRow.getInteger("INDUSTRY"))
				.setType(sqlRow.getInteger("TYPE"))
				.setLogoKey(sqlRow.getString("LOGO_KEY"))
				.setZipCode(sqlRow.getString("ZIPCODE"))
				.setTel(sqlRow.getString("TEL"))
				.setFax(sqlRow.getString("FAX"))
				.setEmail(sqlRow.getString("EMAIL"))
				.setContact(sqlRow.getString("CONTACT"))
				.setPostCount(sqlRow.getInteger("POST_COUNT"))
				.setPayRange(sqlRow.getString("PAY_RANGE"))
				.setWxUrl(sqlRow.getString("WX_URL"))
				.setSortValue(sqlRow.getLong("SORT_VALUE"))
				.setDescr(sqlRow.getString("DESCR"))
				.setIsValid(sqlRow.getInteger("IS_VALID"))
				.setCreateAt(sqlRow.getLong("CREATE_AT"))
				.setUpdateAt(sqlRow.getLong("CREATE_AT"));
		return result;
	}
	
	// DB:根据ID获取Org
	public static Org findFromDBById(Database db, Jedis jedis, String id) {
		Org org = null;
		EbeanServer es = db.getDbByPartitionKey("CAREERX", "");
		StringBuffer sqlStr = new StringBuffer();
		sqlStr.append("SELECT * FROM CX_ORG WHERE IS_VALID<>-1 AND ID=:id");
		SqlQuery sqlQuery = es.createSqlQuery(sqlStr.toString()).setParameter("id", id);
		try {
			SqlRow sqlRow = sqlQuery.findUnique();
			if (sqlRow == null || sqlRow.size()==0) {
				return org;
			}
			org = fromDbRow(sqlRow);
			org.toRedis(jedis);
		} catch (Exception e) {
			logger.error("Error persist Org to findFromDBById : ", e);
		}
		return org;
	}
	
	// DB:根据ID获取Org
	public static Org findAllFromDBById(Database db, String id) {
		Org org = null;
		EbeanServer es = db.getDbByPartitionKey("CAREERX", "");
		StringBuffer sqlStr = new StringBuffer();
		sqlStr.append("SELECT * FROM CX_ORG WHERE ID=:id");
		SqlQuery sqlQuery = es.createSqlQuery(sqlStr.toString()).setParameter("id", id);
		try {
			SqlRow sqlRow = sqlQuery.findUnique();
			if (sqlRow == null || sqlRow.size()==0) {
				return org;
			}
			org = fromDbRow(sqlRow);
		} catch (Exception e) {
			logger.error("Error persist Org to findAllFromDBById : ", e);
		}
		return org;
	}
	
	//获得Org
	public static Org findFromRedisWithDbById(Database db, Jedis jedis, String id) {
		Org org = findFromRedisById(jedis, id);
		if (org == null) {
			org = findFromDBById(db, jedis, id);
		}
		return org;
	}
	
	//获得Org
	public static Org findAllFromRedisWithDbById(Database db, Jedis jedis, String id) {
		Org org = findFromRedisById(jedis, id);
		if (org == null) {
			org = findAllFromDBById(db, id);
		}
		return org;
	}
	
	//批量获得Org
	public static ArrayList<Org> getOrgByIds( Database db, Jedis jedis, String[] orgIds ){
		ArrayList<Org> result = null;
		if (orgIds!=null && orgIds.length>0) {
			result = new ArrayList<Org>();
			for( String id : orgIds ){
				Org org = findFromRedisWithDbById(db, jedis, id);
				if (org != null) {
					result.add(org);
				}
			}
		}
		return result;
	}
	
	//批量获得Org
	public static ArrayList<Org> getAllOrgByIds( Database db, Jedis jedis, String[] orgIds ){
		ArrayList<Org> result = null;
		if (orgIds!=null && orgIds.length>0) {
			result = new ArrayList<Org>();
			for( String id : orgIds ){
				Org org = findAllFromRedisWithDbById(db, jedis, id);
				if (org != null) {
					result.add(org);
				}
			}
		}
		return result;
	}
	
	//根据checkName模糊查询OrgId
//	public static List<String> getOrgIdByCheckName(Database db, Jedis jedis, String checkName){
//		EbeanServer es = db.getDbByPartitionKey("CAREERX", "");
//		StringBuffer sqlStr = new StringBuffer();
//		sqlStr.append("SELECT * FROM CX_ORG WHERE IS_VALID<>-1");
//		sqlStr.append(" AND NAME LIKE :name");
//		SqlQuery sqlQuery = es.createSqlQuery(sqlStr.toString())
//				.setParameter("name", "%"+checkName+"%");
//		try{
//			List<SqlRow> sqlRow = sqlQuery.findList();
//			if (sqlRow==null || sqlRow.size()==0) {
//				return null;
//			}
//			List<String> result = new ArrayList<String>();
//			for( SqlRow sqlItem : sqlRow ){
//				result.add(sqlItem.getString("ID"));
//			}
//			return result;
//		}catch( Exception e ){
//			logger.error("Error persist Org to getOrgIdByCheckName : ", e);
//		}
//		return null;
//	}
	
//	//获得Name和CheckName匹配的字符串
//	public static String getOrgAndLeagueIdByCheckName(Database db, Jedis jedis, String checkName){
//		StringBuffer result = new StringBuffer();
//		List<String> orgIds = getOrgIdByCheckName(db, jedis, checkName);
//		if (orgIds!=null && orgIds.size()>0) {
//			for( String orgId : orgIds ){
//				result.append("'"+orgId+"',");
//			}
//		}
//		List<String> leagueIds = League.getLeagueIdByCheckName(db, jedis, checkName);
//		if (leagueIds!=null && leagueIds.size()>0) {
//			for( String leagueId : leagueIds ){
//				result.append("'"+leagueId+"',");
//			}
//		}
//		if (result==null || result.length()==0) {
//			return null;
//		} else{
//			return result.toString().substring(0, result.length()-1);
//		}
//	}
	
	//判断该名称是否存在
	public static int checkName(Database db, Jedis jedis, String id, String name){
		int result = 0;
		EbeanServer es = db.getDbByPartitionKey("CAREERX", "");
		StringBuffer sqlStr = new StringBuffer();
		sqlStr.append("SELECT * FROM CX_ORG WHERE IS_VALID<>-1 AND NAME=:name");
		if (id!=null && !id.equals("")) {
			sqlStr.append(" AND ID<>:id");
		}
		SqlQuery sqlQuery = es.createSqlQuery(sqlStr.toString())
				.setParameter("name", name)
				.setParameter("id", id);
		try {
			List<SqlRow> sqlRow = sqlQuery.findList();
			if (sqlRow==null || sqlRow.size()==0) {
				result = 0;
			}
			else{
				result = 1;
			}
		} catch (Exception e) {
			logger.error("Error persist Org to checkName : ", e);
		}
		return result;
	}

	//判断该简称是否存在
	public static int checkAbbr(Database db, Jedis jedis, String id, String abbr) {
		int result = 0;
		EbeanServer es = db.getDbByPartitionKey("CAREERX", "");
		StringBuffer sqlStr = new StringBuffer();
		sqlStr.append("SELECT * FROM CX_ORG WHERE IS_VALID<>-1 AND ABBR=:abbr");
		if (id!=null && !id.equals("")) {
			sqlStr.append(" AND ID<>:id");
		}
		SqlQuery sqlQuery = es.createSqlQuery(sqlStr.toString())
				.setParameter("abbr", abbr)
				.setParameter("id", id);
		try {
			List<SqlRow> sqlRow = sqlQuery.findList();
			if (sqlRow==null || sqlRow.size()==0) {
				result = 0;
			} else {
				result = 1;
			}
		} catch (Exception e) {
			logger.error("Error persist Org to checkAbbr : ", e);
		}
		return result; 
	}
	
	//创建Org
	public static int toDb( Database db, Jedis jedis, Client client, Org org, Date currTime ){
		EbeanServer es = db.getDbByPartitionKey("CAREERX", "");
		StringBuffer sqlStr = new StringBuffer();
		sqlStr.append("INSERT INTO CX_ORG(ID,NAME,ABBR,LOCATION_ID,ADDRESS,SIZE,INDUSTRY,TYPE,LOGO_KEY,ZIPCODE,TEL,FAX,EMAIL,CONTACT,POST_COUNT,PAY_RANGE,WX_URL,SORT_VALUE,DESCR,IS_VALID,CREATE_AT,UPDATE_AT)"+
				" VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? )");
		SqlUpdate sqlUpdate = es.createSqlUpdate(sqlStr.toString())
				.setParameter(1, org.getId())
				.setParameter(2, org.getName())
				.setParameter(3, org.getAbbr())
				.setParameter(4, org.getLocationId())
				.setParameter(5, org.getAddress())
				.setParameter(6, org.getSize())
				.setParameter(7, org.getIndustry())
				.setParameter(8, org.getType())
				.setParameter(9, org.getLogoKey())
				.setParameter(10, org.getZipCode())
				.setParameter(11, org.getTel())
				.setParameter(12, org.getFax())
				.setParameter(13, org.getEmail())
				.setParameter(14, org.getContact())
				.setParameter(15, org.getPostCount())
				.setParameter(16, org.getPayRange())
				.setParameter(17, org.getWxUrl())
				.setParameter(18, org.getSortValue())
				.setParameter(19, org.getDescr())
				.setParameter(20, org.getIsValid())
				.setParameter(21, currTime)
				.setParameter(22, currTime);
		try{
			int result = sqlUpdate.execute();
			org = findAllFromDBById(db, org.getId());
			//添加Redis
			org.toRedis(jedis);
			//添加索引
			org.toEs(client);
			return result;
		}catch(Exception e){
			logger.error("Error persist Org to toDb : ", e);
		}
		return 0;
	}
	
	//更新Org
	public static int update( Database db, Jedis jedis, Client client, Org org, Date currTime ){
		if(org.getId() == null){
			return 0;
		}
		EbeanServer es = db.getDbByPartitionKey("CAREERX", "");
		StringBuffer sqlStr = new StringBuffer();
		sqlStr.append("UPDATE CX_ORG SET ");
		sqlStr.append(" NAME= :name,");
		sqlStr.append(" ABBR= :abbr,");
		sqlStr.append(" LOCATION_ID= :locationId,");
		sqlStr.append(" ADDRESS= :address,");
		sqlStr.append(" SIZE= :size,");
		sqlStr.append(" INDUSTRY= :industry,");
		sqlStr.append(" TYPE= :type,");
		if(org.getLogoKey()!=null && !org.getLogoKey().equals("")){
			sqlStr.append(" LOGO_KEY= :logoKey,");
		}
		sqlStr.append(" ZIPCODE= :zipCode,");
		sqlStr.append(" TEL= :tel,");
		sqlStr.append(" FAX= :fax,");
		sqlStr.append(" EMAIL= :email,");
		sqlStr.append(" CONTACT= :contact,");
		sqlStr.append(" PAY_RANGE= :payRange,");
		sqlStr.append(" WX_URL= :wxUrl,");
		sqlStr.append(" SORT_VALUE= :sortValue,");
		sqlStr.append(" DESCR= :descr,");
		sqlStr.append(" UPDATE_AT= :updateAt");
		sqlStr.append(" WHERE IS_VALID<>-1 AND ID=:id");
		SqlUpdate sqlUpdate = es.createSqlUpdate(sqlStr.toString())
				.setParameter("name", org.getName())
				.setParameter("abbr", org.getAbbr())
				.setParameter("locationId", org.getLocationId())
				.setParameter("address", org.getAddress())
				.setParameter("size", org.getSize())
				.setParameter("industry", org.getIndustry())
				.setParameter("type", org.getType())
				.setParameter("logoKey", org.getLogoKey())
				.setParameter("zipCode", org.getZipCode())
				.setParameter("tel", org.getTel())
				.setParameter("fax", org.getFax())
				.setParameter("email", org.getEmail())
				.setParameter("contact", org.getContact())
				.setParameter("payRange", org.getPayRange())
				.setParameter("wxUrl", org.getWxUrl())
				.setParameter("sortValue", org.getSortValue())
				.setParameter("descr", org.getDescr())
				.setParameter("updateAt", currTime)
				.setParameter("id", org.getId());
		
		try{
			int result = sqlUpdate.execute();
			//添加Redis
			org = findAllFromDBById(db, org.getId());
			org.toRedis(jedis);
			//添加索引
			org.toEs(client);
			
			return result;
		}catch(Exception e){
			logger.error("Error persist Org to update : ", e);
		}
		return 0;
	}
	
	//更新职位数
	public static int updatePostCount(Database db, Jedis jedis, Client client, String id, int postCount) {
		if (id == null) {
			return 0;
		}
		EbeanServer es = db.getDbByPartitionKey("CAREERX", "");
		StringBuffer sqlStr = new StringBuffer();
		sqlStr.append("UPDATE CX_ORG SET POST_COUNT= POST_COUNT+:postCount WHERE ID=:id");
		SqlUpdate sqlUpdate = es.createSqlUpdate(sqlStr.toString())
				.setParameter("postCount", postCount)
				.setParameter("id", id);

		try {
			int result = sqlUpdate.execute();
			Org org = findFromDBById(db, jedis, id);
			//添加Redis
			org.toRedis(jedis);
			//添加索引
			org.toEs(client);
			return result;
		} catch (Exception e) {
			logger.error("Error persist Org to updatePostCount : ", e);
		}
		return 0;
	}
	
	// 根据ID判断数据库中是否存在
	public static boolean IsExistFromDBById(Database db, Jedis jedis, String id) {
		EbeanServer es = db.getDbByPartitionKey("CAREERX", "");
		StringBuffer sqlStr = new StringBuffer();
		sqlStr.append("SELECT * FROM CX_ORG WHERE ID=:id");
		SqlQuery sqlQuery = es.createSqlQuery(sqlStr.toString()).setParameter("id", id);
		try {
			SqlRow sqlRow = sqlQuery.findUnique();
			if (sqlRow == null || sqlRow.size()==0) {
				return false;
			}
			return true;
		} catch (Exception e) {
			logger.error("Error persist Org to IsExistFromDBById : ", e);
		}
		return false;
	}
	
	//根据ID删除Org
	public static int deleteById( Database db, Jedis jedis, Client client, String id ){
		if(id==null || id.equals("") || IsExistFromDBById(db, jedis, id)==false){
			return 0;
		}
		try {
			StringBuffer sqlStr = new StringBuffer();
			sqlStr.append("UPDATE CX_ORG SET IS_VALID=-1 WHERE IS_VALID<>-1 AND ID=?");
			EbeanServer es = db.getDbByPartitionKey("CAREERX", id);
			SqlUpdate sqlUpdate = es.createSqlUpdate(sqlStr.toString())
					.setParameter(1, id);
			int result = sqlUpdate.execute();
			Org org = findAllFromDBById(db, id);
			//删除Redis
			deleteRedis(jedis, org);
			//更新索引
			org.toEs(client);
			return result;
		} catch (Exception e) {
			logger.error("Error persist Org to deleteOrgById : ", e);
		}
		return 0;
	}
	
	//根据ID停用Org
	public static int disableById( Database db, Jedis jedis, Client client, String id ){
		if(id==null || id.equals("") || IsExistFromDBById(db, jedis, id)==false){
			return 0;
		}
		try {
			StringBuffer sqlStr = new StringBuffer();
			sqlStr.append("UPDATE CX_ORG SET IS_VALID=0 WHERE IS_VALID<>-1 AND ID=?");
			EbeanServer es = db.getDbByPartitionKey("CAREERX", id);
			SqlUpdate sqlUpdate = es.createSqlUpdate(sqlStr.toString())
					.setParameter(1, id);
			int result = sqlUpdate.execute();
			Org org = findAllFromDBById(db, id);
			//删除Redis
			deleteRedis(jedis, org);
			//更新索引
			org.toEs(client);
			return result;
		} catch (Exception e) {
			logger.error("Error occurred in Org for disabledOrgById = ", e);
		}
		return 0;
	}
	
	//根据ID启用Org
	public static int enableById( Database db, Jedis jedis, Client client, String id ){
		if(id==null || id.equals("") || IsExistFromDBById(db, jedis, id)==false){
			return 0;
		}
		try {
			StringBuffer sqlStr = new StringBuffer();
			sqlStr.append("UPDATE CX_ORG SET IS_VALID=1 WHERE IS_VALID=0 AND ID=?");
			EbeanServer es = db.getDbByPartitionKey("CAREERX", id);
			SqlUpdate sqlUpdate = es.createSqlUpdate(sqlStr.toString())
					.setParameter(1, id);
			int result = sqlUpdate.execute();
			Org org = findAllFromDBById(db, id);
			//删除Redis
			org.toRedis(jedis);
			//更新索引
			org.toEs(client);
			return result;
		} catch (Exception e) {
			logger.error("Error occurred in Org for enableOrgById = ", e);
		}
		return 0;
	}
	
	//批量删除Org
	public static int deleteByIds( Database db, Jedis jedis, Client client, String[] idList ){
		int result = 0;
		for( String id : idList ){
			deleteById( db, jedis, client, id );
			result ++;
		}
		return result;
	}
	
	//批量停用Org
	public static int disableByIds( Database db, Jedis jedis, Client client, String[] idList ){
		int result = 0;
		for( String id : idList ){
			disableById( db, jedis, client, id );
			result ++;
		}
		return result;
	}
	
	//批量启用Org
	public static int enableByIds( Database db, Jedis jedis, Client client, String[] idList ){
		int result = 0;
		for( String id : idList ){
			enableById( db, jedis, client, id );
			result ++;
		}
		return result;
	}
	
	public static String getNameByIdType(Database db, String id, int type){
		String result = null;
		EbeanServer es = db.getDbByPartitionKey("CAREERX", "");
		StringBuffer sqlStr = new StringBuffer();
		sqlStr.append("SELECT * FROM");
		if (type == 4) {
			sqlStr.append(" CX_LEAGUE WHERE ID=:id");
		} else{
			sqlStr.append(" CX_ORG WHERE ID=:id");
		}
		SqlQuery sqlQuery = es.createSqlQuery(sqlStr.toString())
				.setParameter("id", id);
		try {
			SqlRow sqlRow = sqlQuery.findUnique();
			if (sqlRow==null || sqlRow.equals("")) {
				result = null;
			}
			else{
				result = sqlRow.getString("NAME");
			}
		} catch (Exception e) {
			logger.error("Error persist Org to getNameByIdType : ", e);
		}
		return result;
	}
	
}
